<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";

// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Array,
    default: () => [
      { value: 1, name: "已评分" },
      { value: 1, name: "待评分" },
      { value: 1, name: "未完成" }
    ],
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 2. 封装初始化图表的函数（复用）
const initChart = (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  const option = {
    color: ["#00C090", "#FF7024", "#E6EBF1"],
    title: [
      {
        text: "总计",
        left: "50%",
        textAlign: "center",
        textVerticalAlign: "middle",
        top: "40%",
        textStyle: {
          fontSize: 12,
          color: "#8C8C8C",
        },
      },
      {
        // 成交金额文本
        text: props.data.reduce((total, item) => total + item.value, 0),
        left: "50%",
        top: "60%",
        textAlign: "center",
        textVerticalAlign: "middle",
        textStyle: {
          fontSize: 24,
          color: "#262626",
          lineHeight: 36,
        },
      },
    ],
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      show: true,
      left: 'center',
      top: 10,
      itemGap: 10,
      itemWidth: 12,
      itemHeight: 12,
    },
    series: [
      {
        name: "",
        label: {
          show: false,
        },
        type: "pie",
        center: ["50%", "56%"],
        radius: ["56%", "76%"],
        data: props.data,
      },
    ],
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

watch(
  () => props.data,
  () => initChart()
);
</script>

<style scoped>
.chart-container {
  width: 100%; /* 自适应父容器宽度 */
  height: 100%;
}
</style>
